package main

import (
	"fmt"
	"strconv"
	"time"
)

type FakeTimer struct {
	timersMap map[int]*time.Timer
	chCloseMap map[int]chan bool
}

func main(){

	fTimer := new(FakeTimer)
	fTimer.timersMap = make(map[int]*time.Timer)
	fTimer.chCloseMap = make(map[int]chan bool)
	for i :=0 ; i<10 ;i++{
		fTimer.CreateTimer(i,i)
	}
	fmt.Printf("计时器数量%v \n",len(fTimer.timersMap))
	time.Sleep(2*time.Second)
	fmt.Println("开始手动stop计时器")
	fTimer.StopTimer(7)
	fmt.Printf("手动stop后，计时器数量%v \n",len(fTimer.timersMap))

	time.Sleep(15*time.Second)
	fmt.Printf("最后还剩计时器数：%v \n",len(fTimer.timersMap))
}


func(fakeTimer *FakeTimer)CreateTimer(timeout int,timeId int){
	timerInstance := time.NewTimer(time.Duration(timeout)*time.Second)
	//	time.AfterFunc(time.Duration(timeout)*time.Second, func() {
	//	fakeTimer.OnTimerOut("倒计时到了",timeId)
	//})
	fakeTimer.timersMap[timeId] = timerInstance
	var chClose = make(chan bool)
	fakeTimer.chCloseMap[timeId] = chClose
	go func(timeId int) {
		select {
			case <- timerInstance.C:
				fakeTimer.OnTimerOut("倒计时到了",timeId)
			case <- chClose:
				fmt.Println("+++++++++++++return++++++++++")
				return
		}
	}(timeId)
}

func(fakeTimer *FakeTimer)StopTimer(key int){
	if timer,ok := fakeTimer.timersMap[key];ok{
		//close(fakeTimer.chCloseMap[key])
		//fmt.Println("Stop Result:"+strconv.FormatBool(timer.Stop()))
		fmt.Println(len(timer.C))
		if timer.Stop() {
			fmt.Println("stop success")
			fakeTimer.OnTimerOut("倒计中途手动停止",key)
			delete(fakeTimer.timersMap,key)
		}else{
			<- timer.C
			fmt.Println("停止倒计时器失败")
		}
	}else{
		fmt.Println("没有key为"+strconv.Itoa(key)+"的倒计时器")
	}
}

func(fakeTimer *FakeTimer)OnTimerOut(msg string,timeId int){
	fmt.Println(msg+strconv.Itoa(timeId))
	delete(fakeTimer.timersMap,timeId)
}

